package com.nexgo.payment.action.queryresp;

import android.content.Context;
import android.os.Bundle;
import android.text.TextUtils;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.Button;
import android.widget.TextView;

import com.nexgo.payment.R;
import com.nexgo.payment.action.Action;
import com.nexgo.payment.action.ActionResult;
import com.nexgo.payment.action.ActionStep;
import com.nexgo.payment.action.OnActionListener;
import com.nexgo.payment.constrant.SysConstant;
import com.nexgo.payment.databases.Repository;
import com.nexgo.payment.entity.TransData;
import com.nexgo.payment.ui.BaseFragment;
import com.nexgo.payment.util.StringUtils;
import com.nexgo.payment.util.TransUtils;
import com.nexgo.payment.widget.ItemLinearLayout;
import com.nexgo.payment.widget.TitleBuilder;

import java.text.SimpleDateFormat;
import java.util.Date;

import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.OnClick;
import butterknife.Unbinder;
import java8.util.Optional;

/**
 * 输入日期界面
 *
 * @author 谭忠扬-YuriTam
 * @time 2017年8月25日
 */
public class QueryRespFragment extends BaseFragment implements Action<ActionStep>, QueryRespContract.View, BaseFragment.DownTimerListener {
    private static final String TRANS_DATA = "transData";

    @BindView(R.id.tv_balance_type)
    TextView tvBalanceType;
    @BindView(R.id.tv_amount)
    TextView tvAmount;
    @BindView(R.id.item_trade_type)
    ItemLinearLayout mTradeType;   //交易类型
    @BindView(R.id.item_card_no)
    ItemLinearLayout mCardNo;      //卡号
    @BindView(R.id.item_date_time)
    ItemLinearLayout mTradeTime;   //交易时间
    @BindView(R.id.btn_back_2_main)
    Button btnBack2Main;
    Unbinder unbinder;

    private OnActionListener mListener;
    private QueryRespContract.Presenter mPresenter;

    public QueryRespFragment() {
        // Required empty public constructor
    }

    public static QueryRespFragment newInstance(TransData transData) {
        QueryRespFragment fragment = new QueryRespFragment();
        Bundle args = new Bundle();
        args.putParcelable(TRANS_DATA, transData);
        fragment.setArguments(args);
        return fragment;
    }

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        TransData transData = null;
        if (getArguments() != null) {
            transData = getArguments().getParcelable(TRANS_DATA);
        }
        new QueryRespPresenter(this, Repository.getInstance(), transData);
    }

    @Override
    protected View initView(LayoutInflater inflater, ViewGroup container) {
        View view = inflater.inflate(R.layout.fragment_balance, container, false);
        unbinder = ButterKnife.bind(this, view);

        initTitle(view);

        return view;
    }

    //初始化标题栏
    private void initTitle(View view) {
        new TitleBuilder(view)
                .setLeftImage(R.drawable.arrow_icon)
                .setTitleText(getString(R.string.balance_title))
                .build();
    }

    @Override
    protected void initEvent() {
    }

    @Override
    protected void initData() {
    }

    @Override
    public void onResume() {
        super.onResume();
        mPresenter.start();
    }

    @OnClick({R.id.title_iv_left, R.id.btn_back_2_main})
    public void onClick(View view) {
        switch (view.getId()) {
            case R.id.title_iv_left:
            case R.id.btn_back_2_main:
                if (mListener != null) {
                    mListener.setActionResult(new ActionResult(this, ActionResult.SUCC, null));
                }
                break;
            default:
                break;
        }
    }

    @Override
    public void onAttach(Context context) {
        super.onAttach(context);
        if (context instanceof OnActionListener) {
            mListener = (OnActionListener) context;
        }
    }

    @Override
    public ActionStep getActionStep() {
        return ActionStep.QUERY_RESP;
    }

    @Override
    public void setPresenter(QueryRespContract.Presenter presenter) {
        mPresenter = presenter;
    }

    @Override
    public void showQueryResp(TransData transData) {
        //查询类型描述
        switch (transData.getTransType()) {
            case QUERY:
                tvBalanceType.setText(getString(R.string.balance_tips));
                break;
            case EC_BALANCE:
                tvBalanceType.setText(getString(R.string.ec_balance_tips));
                break;
            default:
                break;
        }
        //余额
        String symbol = Optional.ofNullable(transData.getTemporary())
                .map(s -> {
                    if (!"C".equals(s)) {
                        return "-";
                    } else {
                        return "";
                    }
                }).orElse("");
        tvAmount.setText(String.format("%s%s", symbol, StringUtils.formatAmount(transData.getAmount(), 2)));
        //交易类型
        mTradeType.setRightText(transData.getTransType().getName());
        //卡号
        Optional.ofNullable(transData.getPan())
                .filter(s -> !TextUtils.isEmpty(s))
                .ifPresent(s -> {
                    mCardNo.setVisibility(View.VISIBLE);
                    mCardNo.setRightText(TransUtils.maskPan(s));
                });
        //统一显示当前时间
        mTradeTime.setRightText(new SimpleDateFormat("yyyy-MM-dd HH:mm:ss", SysConstant.LOCALE).format(new Date()));

        //启动倒计时
        setDownTimer(SysConstant.TIME_OUT_5, this);
    }

    @Override
    public boolean isActive() {
        return isAdded();
    }

    @Override
    public void onDestroyView() {
        super.onDestroyView();
        cancelDownTimer();
        unbinder.unbind();
    }

    @Override
    public void onTick(long secondsUntilFinished) {
        if (!isActive()) {
            return;
        }
        btnBack2Main.setText(getString(R.string.back_to_main_layout) + "（" + secondsUntilFinished + "）");
    }

    @Override
    public void onFinish() {
        if (isActive()) {
            btnBack2Main.setText(getString(R.string.back_to_main_layout) + "（0）");
        }
        if (mListener != null) {
            mListener.setActionResult(new ActionResult(this, ActionResult.SUCC, null));
        }
    }
}
